<template>
  <div class="wrapper">
    <div>
      <elements @addElementTag="onAddElement" />
    </div>
    <div>
      <div class="titleContent">
        <div class="title title5" data-text="HTML标签">表单设计</div>
        <input type="button" @click="onExportHTML" value="导出HTML" class="button" />
        <input type="button" @click="onExportJson" value="导出JSON" class="button" />
        <slot name="toolbar"></slot>
        <!-- <input type="button" @click="onSaveJson" value="保存" class="button" /> -->
      </div>
      <div id="formRener">
        <form id="generatedForm">
          <drag-control
            v-for="(obj, index) in list"
            :key="index"
            :item="obj"
            :class="['definedForm', obj.type == 'div' ? 'spliter-' + obj.cx : '']"
            draggable="true"
            @dragleave="onDragLeave"
            @drop="(event) => onDrop(event, obj)"
            @dragstart.self="(event) => onDragStart(event, obj)"
            @dragover.self="onDragOver"
            @elementSelected="onSelected"
          >
            <template #item="childrenSlot">
              <!-- <span>{{ childrenSlot.item }}</span> -->
              <drag-control
                :key="index"
                :item="childrenSlot.item"
                class="definedForm"
                draggable="true"
                @dragleave="onDragLeave"
                @drop="(event) => onDrop(event, childrenSlot.item)"
                @dragstart.self="(event) => onDragStart(event, childrenSlot.item)"
                @dragover.self="onDragOver"
                @elementSelected="onSelected"
              />
            </template>
          </drag-control>
        </form>
      </div>
    </div>
    <div>
      <properties
        v-model="curProp"
        @removeElementTag="onRemoveTag"
        @updateProperty="onUpdateProperty"
      />
    </div>
  </div>
</template>

<script>
import { toRaw } from "vue";
import i18n from "@/i18n/index";
import { move, remove, update } from "@/assets/lib/helper";
import Elements from "./controls/Elements.vue";
import Properties from "./controls/Properties.vue";
import DragControl from "./controls/DragControl.vue";
import { saveAs } from "file-saver";

export default {
  name: "FormBuilder",
  components: {
    Elements,
    Properties,
    DragControl,
  },
  data() {
    return {
      curElement: null,
      curProp: {},
      list: [],
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    $t(key, value) {
      return i18n.global.t(key, value);
    },
    init() {
      console.log("使用i18n");
    },
    onAddElement(e) {
      this.list.push(e);
    },
    onDragStart(e, obj) {
      e.dataTransfer.setData("item-dragging", JSON.stringify(obj));
    },
    onDragOver(e) {
      e.preventDefault();
      // if (e.target.tagName.toLowerCase() == "div")
      event.target.style.border = "1px dashed green";
    },
    onDragLeave(e) {
      e.preventDefault();
      event.target.style.border = "0 dashed #000";
    },
    onDrop(e, obj) {
      e.preventDefault();
      event.target.style.border = "0 dashed #000";
      var data = JSON.parse(e.dataTransfer.getData("item-dragging"));
      // 如果是自己，什么也不动
      if (data.index === obj.index) {
        return;
      }
      // 不能将容器放入div中
      if (data.type === "div" && obj.type === "div") {
        return;
      }
      // 把当前元素删除
      remove(this.list, data);
      if (obj.type != "div") {
        // 插入新元素
        move(this.list, data, obj);
      } else {
        // 吸入到div中
        if (!obj.children) {
          obj.children = [];
        }
        obj.children.push(data);
      }
    },
    onSelected(e) {
      this.curProp = e.item;
      e.target.style.border = "1px solid green";
      e.target.style.borderRadius = "3px";
      if (this.curElement) {
        this.curElement.style.border = "";
      }
      this.curElement = e.target;
    },
    onRemoveTag(tag) {
      remove(this.list, tag);
      // this.list.splice(this.list.indexOf(tag), 1);
    },
    onUpdateProperty(event) {
      console.log(event);
      update(this.list, event);
    },
    exportJson() {
      return this.list;
    },
    exportHTML() {
      return document.querySelector("#formRener").innerHTML;
    },
    changeLang(lang) {
      i18n.locale = lang || "zh";
    },
    onExportHTML() {
      let html = document.querySelector("#formRener");
      var file = new File([html.innerHTML], "form.txt", {
        type: "text/plain;charset=utf-8",
      });
      saveAs(file);
    },
    onExportJson() {
      let json = this.list;
      var file = new File([JSON.stringify(toRaw(json))], "form.json", {
        type: "text/plain;charset=utf-8",
      });
      saveAs(file);
    },
    onSaveJson() {
      let json = this.list;
      localStorage.setItem("formx", JSON.stringify(toRaw(json)));
    },
  },
};
</script>

<style>
@import "@/assets/style/smart-green.css";
@import "@/assets/style/base.css";
@import "@/assets/style/title.css";
.icon-color {
  font-size: 50px !important;
  color: yellow;
}
</style>
